﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace RssTools
{
    class Program
    {
        static void Main(string[] args)
        {
            var options = new Options();
            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                if (!String.IsNullOrEmpty(options.Command) && options.Command.ToLower() != "put")
                    throw new NotImplementedException("Implement only put command");

                var xml = new XmlDocument();

                if (File.Exists(options.InputFile))
                {
                    xml.Load(options.InputFile);
                }
                else
                {
                    xml.LoadXml(@"<rss version='2.0'><channel /></rss>");
                }
                
                var xmlNewEntry = CreateElement((XmlElement)xml.SelectSingleNode("/rss/channel"), "item");
                if (!String.IsNullOrEmpty(options.FeedItemTitle))
                {
                    CreateElement(xmlNewEntry, "title").InnerText = options.FeedItemTitle;
                }
                if (!String.IsNullOrEmpty(options.FeedItemLink))
                {
                    CreateElement(xmlNewEntry, "link").InnerText = options.FeedItemLink;
                }
                if (!String.IsNullOrEmpty(options.FeedItemGuid))
                {
                    CreateElement(xmlNewEntry, "guid").InnerText = options.FeedItemGuid;
                }
                if (!String.IsNullOrEmpty(options.FeedItemDescription))
                {
                    CreateElement(xmlNewEntry, "description").InnerText = options.FeedItemDescription;
                }

                CreateElement(xmlNewEntry, "pubDate").InnerText = DateTime.Now.ToString("R");

                xml.Save(String.IsNullOrWhiteSpace(options.OutputFile) ? options.InputFile : options.OutputFile);
            }
        }

        private static XmlElement CreateElement(XmlElement parent, string tag)
        {
            if (parent.OwnerDocument == null)
            {
                throw new ArgumentNullException("parent");
            }
            var a = parent.OwnerDocument.CreateElement(tag);
            parent.AppendChild(a);
            return a;
        }
    }
}
